const pageSize = 4;
cc.Class({
    extends: cc.Component,

    properties: {
        content: cc.Node,
        itme: cc.Node,
    },


    onEnable() {
        this.lobbyMain = cc.find("Canvas").getComponent("lobbyMain");
        this.lobbyNet = this.lobbyMain.lobbyNet;
        this.playerInfo = this.lobbyMain.playerInfo;

        this.yeNum = 1  //页数
        this.betInfo = null;

        this.btnLeft = this.node.getChildByName("recordBg1").getChildByName("hisBottom").getChildByName("email_left").getComponent(cc.Button);
        this.btnRight = this.node.getChildByName("recordBg1").getChildByName("hisBottom").getChildByName("email_right").getComponent(cc.Button);
        this.btnLeft.interactable = false;

        this.selectTime = this.node.getChildByName("recordBg1").getChildByName("hisTop").getChildByName("selectTime")
        this.selectDay = 1;  //查看几天
        this.isSelectTime = false;

        this.totalNode = this.node.getChildByName("recordBg1").getChildByName("hisTop").getChildByName("total");

        this.yeLabel = this.node.getChildByName("recordBg1").getChildByName("hisBottom").getChildByName("email_page").getChildByName("label").getComponent(cc.Label);
        this.fenleNode = this.node.getChildByName("recordBg1").getChildByName("hisTop").getChildByName("fenlei")
        this.gameTypeNode = this.fenleNode.getChildByName("gameType");
        this.gameTypeNode.active = false;
        this.gameType = "all"

        this.getBetHistory(); //从服务器获取记录的

    },



    onClick(event, target) {
        this.lobbyMain.playClickSound();
        if (target == "close") {//关闭页面
            this.closePanel();
        } else if (target == "left") { //上一页
            if (this.yeNum == 1) {
                this.btnLeft.interactable = false;
                return;
            }
            this.yeNum = this.yeNum - 1
            this.lodaBetPrefab();
        } else if (target == "right") {//下一页
            this.yeNum = this.yeNum + 1
            this.btnLeft.interactable = true;
            this.lodaBetPrefab();
        } else if (target == "day1" || target == "day3" || target == "day7" || target == "day15" || target == "day30") {  //切换日期
            this.changeDate(target);
        } else if (target == "chooseGame") {  //选择游戏类型
            this.gameTypeNode.active = !this.gameTypeNode.active;
            this.fenleNode.getChildByName("up").active = !this.fenleNode.getChildByName("up").active;
            this.fenleNode.getChildByName("down").active = !this.fenleNode.getChildByName("down").active;
        } else if (target == "all" || target == "fish" || target == "slot" || target == "other") { //游戏类型
            this.gameType = target;
            this.gameTypeNode.active = !this.gameTypeNode.active;
            this.fenleNode.getChildByName("up").active = !this.fenleNode.getChildByName("up").active;
            this.fenleNode.getChildByName("down").active = !this.fenleNode.getChildByName("down").active;
            this.fenleNode.getChildByName("label").getComponent(cc.Label).string = target.charAt(0).toUpperCase() + target.slice(1);
            this.getBetHistory();
        }
    },

    getBetHistory() {
        let data = {
            action: "getBetHistory",
            day: this.selectDay,
            playerId: this.playerInfo.playerId,
            gameType: this.gameType
        }
        this.lobbyNet.sendMessage(data);
    },

    //根据日期切换数据
    changeDate(tar) {
        let temp = 0;
        if (tar == "day1") {
            temp = 1;
        } else if (tar == "day3") {
            temp = 3;
        } else if (tar == "day7") {
            temp = 7;
        } else if (tar == "day15") {
            temp = 15;
        } else if (tar == "day30") {
            temp = 30;
        }

        if (!this.isSelectTime) {
            this.selectTime.children.forEach(child => {
                child.active = true;
            });
            this.isSelectTime = !this.isSelectTime;
        } else {
            this.selectTime.children.forEach(child => {
                if (child.name !== tar) {
                    child.active = false;
                }
            });
            this.isSelectTime = !this.isSelectTime;
        }

        if (this.selectDay == temp) {
            return;
        } else {
            this.selectDay = temp
            this.yeNum = 1;
            this.getBetHistory();
        }
    },


    //获取到投注记录后的响应
    onGetBetHistory(data) {
        if (data.respCode == "SUCCESS") {
            this.betInfo = this.formatAndSortBetList(data.data) //根据时间重新排序
            this.handleTotal();
            this.lodaBetPrefab();
        } else {
            this.lobbyMain.showTips("Failed to retrieve betting history. Please try again.")
        }
    },

    closePanel() {
        let callback = () => {
            this.content.removeAllChildren();
        }
        this.lobbyMain.hidePanel(this.node,callback);
    },

    //处理总数
    handleTotal() {
        let totalBet = 0;
        let totalScore = 0;
        let totalWin = 0;
        let totalBetLabel = this.totalNode.getChildByName("totalBet").getChildByName("label")
        let totalWinLabel = this.totalNode.getChildByName("totalWin").getChildByName("label")
        let totalScoreLabel = this.totalNode.getChildByName("totalScore").getChildByName("label")
        for (let i = 0; i < this.betInfo.length; i++) {
            const element = this.betInfo[i];
            totalBet += element.bet;
            totalWin += element.win;
            totalScore += element.winscore
        }
        // totalBetLabel.color = (totalBet / this.playerInfo.ratio >= 0) ? cc.Color.GREEN : cc.Color.RED;
        totalWinLabel.color = (totalWin / this.playerInfo.ratio >= 0) ? cc.Color.GREEN : cc.Color.RED;
        // totalScoreLabel.color = (totalScore / this.playerInfo.ratio >= 0) ? cc.Color.GREEN : cc.Color.RED;

        totalBetLabel.getComponent(cc.Label).string = (totalBet / this.playerInfo.ratio).toFixed(2);
        totalScoreLabel.getComponent(cc.Label).string = (totalScore / this.playerInfo.ratio).toFixed(2);
        totalWinLabel.getComponent(cc.Label).string = (totalWin / this.playerInfo.ratio).toFixed(2);
    },

    formatAndSortBetList(betList) {
        return betList
            .map(item => {
                // 处理 betTime 格式
                const dateObj = new Date(item.betTime);
                item.betTime = dateObj.toLocaleString();

                // 处理 betData 字符串转 JSON
                // try {
                //     item.betData = JSON.parse(item.betData);
                // } catch (e) {
                //     // 如果解析失败，保持原字符串，或者赋值为空对象
                //     item.betData = {};
                //     console.warn('betData 解析失败:', item.betData);
                // }

                return item;
            })
            .sort((a, b) => new Date(b.betTime) - new Date(a.betTime));
    },

    lodaBetPrefab() {
        let length = this.betInfo.length;
        if (length == 0) {
            this.yeLabel.string = "0/0"
        } else {
            if (this.yeNum == Math.ceil(length / 4)) {
                this.yeNum = Math.ceil(length / 4);
                this.btnRight.interactable = false;
            } else {
                this.btnRight.interactable = true;
            }
            if (this.yeNum == 1) {
                this.btnLeft.interactable = false;
            }
            this.yeLabel.string = this.yeNum + "/" + Math.ceil(length / 4)
        }
        this.content.removeAllChildren();

        let startIndex = (this.yeNum - 1) * pageSize;
        let endIndex = this.yeNum * pageSize;
        let currentPageData = this.betInfo.slice(startIndex, endIndex);
        for (let i = 0; i < currentPageData.length; i++) {
            const element = currentPageData[i];
            let betData = element
            let item = cc.instantiate(this.itme);
            // item.getChildByName("gameId").getComponent(cc.Label).string = element.gameId;
            item.getChildByName("gameId").getComponent(cc.Label).string = element.gameName;
            item.getChildByName("bet").getComponent(cc.Label).string = (betData.bet / this.playerInfo.ratio).toFixed(2);
            item.getChildByName("score").getComponent(cc.Label).string = (betData.winscore / this.playerInfo.ratio).toFixed(2);

            let winLoseNode = item.getChildByName("winLose");
            betData.win = parseFloat(betData.win)
            if (betData.win > 0) {
                winLoseNode.getComponent(cc.Label).string = "+" + (betData.win / this.playerInfo.ratio).toFixed(2);
                winLoseNode.color = cc.Color.GREEN;
            } else {
                winLoseNode.getComponent(cc.Label).string = (betData.win / this.playerInfo.ratio).toFixed(2);
                winLoseNode.color = cc.Color.RED;
            }
            item.getChildByName("time").getComponent(cc.Label).string = element.betTime;
            item.getChildByName("orderId").getComponent(cc.Label).string = element.betOrderId;
            this.content.addChild(item);
        }
    },

    // update (dt) {},
});
